#include "cc_encode.h"
#include <windows.h>

void __cdecl cc_ANSI2Unicode(char *ansi, wchar_t **unicode)
{
	int len = 0;
	len = MultiByteToWideChar(CP_ACP, 0, ansi, -1, NULL, 0);
	*unicode = (wchar_t*)cc_calloc(len + 1, sizeof(wchar_t));
	MultiByteToWideChar(CP_ACP, 0, ansi, -1, *unicode, len);
	(*unicode)[len] = 0;
}

void __cdecl cc_Unicode2ANSI(wchar_t *unicode, char **ansi)
{
	int len = 0;
	bool def = false;
	len = WideCharToMultiByte(CP_ACP, 0, unicode, -1, NULL, 0, NULL, &def);
	*ansi = (char*)cc_malloc(len + 1);
	WideCharToMultiByte(CP_ACP, 0, unicode, -1, *ansi, len, NULL, &def);
	(*ansi)[len] = 0;
}

void __cdecl cc_UTF82Unicode(char *utf8, wchar_t **unicode)
{
	int len = 0;
	len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
	*unicode = (wchar_t *)cc_calloc(len + 1, sizeof(wchar_t));
	MultiByteToWideChar(CP_UTF8, 0, utf8, -1, *unicode, len);
	(*unicode)[len] = 0;
}

void __cdecl cc_Unicode2UTF8(wchar_t *unicode, char **utf8)
{
	int len = 0;
	bool def = false;
	len = WideCharToMultiByte(CP_UTF8, 0, unicode, -1, NULL, 0, NULL, &def);
	*utf8 = (char *)cc_malloc(len + 1);
	WideCharToMultiByte(CP_UTF8, 0, unicode, -1, *utf8, len, NULL, &def);
	(*utf8)[len] = 0;
}

int	__cdecl cc_ucs2char_to_utf8( 
	IN wchar_t wch, 
	OUT char *utf8Str
	)
{
	int utf8Len = 0;
	if(wch < 0x80)
		utf8Len = 1;
	else if(wch < 0x800)
		utf8Len = 2;
	else
		utf8Len = 3;

	switch(utf8Len)
	{
	case 3:
		utf8Str[2] = (wch & 0x3F) | 0x80;
		wch >>= 6;
		wch |= 0x800;
	case 2:
		utf8Str[1] = (wch & 0x3F) | 0x80;
		wch >>= 6;
		wch |= 0xC0;
	case 1:
		utf8Str[0] = (char)wch;
		break;
	}

	return utf8Len;
}
